<?php

/**
 * 父类控制器，共同方法注入、登录校验
 */
class CT_Controller extends CI_Controller
{
    public $_open_id;
    public $_uid ;
    public $_nursery_id;
    public $_is_teacher;
    //不需授权的方法
    public $out_method = array('logout','weixin_notify');
    //不需授权的控制器
    public $out_class = array('ajax','cron');
    
    function __construct ()
    {
        parent::__construct();
        
        //运营管理后台
        if($this->router->directory === 'admin/')
        {
            $this->load->library('CT_auth');
            $admin_userinfo = $this->ct_auth->get_admin_user_login();
            $this->_admin_uid = isset($admin_userinfo['admin_uid']) ? $admin_userinfo['admin_uid'] : 0;
            $this->_admin_username = isset($admin_userinfo['admin_username']) ? $admin_userinfo['admin_username'] : '';
        }else if($this->router->directory === 'nursery/')   //园所管理后台
        {
            $this->load->library('CT_auth_nursery');
            $nursery_userinfo = $this->ct_auth_nursery->get_nursery_user_login();
            $this->_nursery_id = isset($nursery_userinfo['nid']) ? $nursery_userinfo['nid'] : 0;
            $this->_nursery_uid = isset($nursery_userinfo['nuid']) ? $nursery_userinfo['nuid'] : 0;
            $this->_nursery_username = isset($nursery_userinfo['nusername']) ? $nursery_userinfo['nusername'] : '';
        }else if($this->router->directory === 'api/'){
            
        }else{
            $this->ct_template->set_template('template_h5');
            
            //用户|老师登陆处理
            $this->load->library('CT_auth_member_teacher');
            $userinfo = $this->ct_auth_member_teacher->get_user_login();
            $this->_open_id = isset($userinfo['open_id']) ? $userinfo['open_id'] : '';
//             $this->_open_id = 'okNb0t9wZ46KKlQ8ZzunxQTmxjLk';
            $class = $this->router->class;
            $method = $this->router->method;
            
            if(!$this->_open_id && !$this->input->is_ajax_request() 
                && !in_array($method, $this->out_method) && !in_array($class, $this->out_class)){
                //微信授权获取用户信息-教师优先
                $wx_uinfo = $this->get_wx_user_info();
                $this->_open_id = $wx_uinfo['openid'];
            }
            
            if($this->_open_id && !isset($userinfo['open_id']) ){
                //微信授权获取用户信息-教师优先
                //优先获取教师信息
                $this->load->model('teacher_model');
                $teacher_info = $this->teacher_model->find(array('wx_open_id'=>$this->_open_id, 'status'=>1));
                //获取用户信息
                $this->load->model('member_model');
                $member_info = $this->member_model->find(array('wx_open_id'=>$this->_open_id, 'status'=>1));
                
                if($teacher_info){
                    $this->_nursery_id = isset($teacher_info['nursery_id']) ? $teacher_info['nursery_id'] : 0;
                    $this->_uid = $teacher_info['is_login'] && $teacher_info['id'] ? $teacher_info['id'] : 0;
                    $this->_is_teacher = 1;
                
                    $this->teacher_model->update(array('update_date'=>date('Y-m-d H:i:s'),'avatar'=>$wx_uinfo['headimgurl']),array('id'=>$teacher_info['id']));
                }else if($member_info) {
                    $this->_nursery_id = isset($member_info['nursery_id']) ? $member_info['nursery_id'] : 0;
                    $this->_uid = $member_info['is_login'] && $member_info['id'] ? $member_info['id'] : 0;
                    $this->_is_teacher = 0;
                
                    $this->member_model->update(array('update_date'=>date('Y-m-d H:i:s'),'wx_avatar'=>$wx_uinfo['headimgurl'],'wx_nick_name'=>$wx_uinfo['nickname']),array('id'=>$member_info['id']));
                }else{
                    $columns = array(
                        'wx_nick_name'=>$wx_uinfo['nickname'],
                        'wx_open_id'=>$this->_open_id,
                        'wx_avatar'=>$wx_uinfo['headimgurl'],
                        'create_date'=>date('Y-m-d H:i:s'),
                    );
                    $insert_id = $this->member_model->insert($columns);
                }
            }else{
                $this->_nursery_id = isset($userinfo['nursery_id']) ? $userinfo['nursery_id'] : 0;
                $this->_uid = isset($userinfo['uid']) ? $userinfo['uid'] : 0;
                $this->_is_teacher = isset($userinfo['is_teacher']) ? $userinfo['is_teacher'] : 0;
            }

            $nursery_id = intval($this->input->get('nursery_id',TRUE));
            if($nursery_id){
                $this->_nursery_id = $nursery_id;
            }
            
            
            //session设置数据
            $sess_user_info = array(
                'id'=>$this->_uid,
                'nursery_id'=>$this->_nursery_id,
                'wx_open_id'=>$this->_open_id,
                'is_teacher'=>$this->_is_teacher
            );
            
            $this->ct_auth_member_teacher->set_user_login($sess_user_info);
            
        }
        
    }
    
    private function get_wx_user_info()
    {
        //是否在微信打开
//         if(preg_match("/MicroMessenger/i",$_SERVER["HTTP_USER_AGENT"])){

            ini_set('date.timezone','Asia/Shanghai');
            require_once (APPPATH . "/third_party/wechat/wxpay/lib/WxPay.JsApiPay.php");
            
            //获取微信用户信息
            $tools = new JsApiPay();
            $wx_user_info = $tools->GetOpenid();
            
            return isset($wx_user_info['openid']) ? $wx_user_info : NUll;
            
//         }
    }  
     
    public function pagination($total, $per_page = 20)
    {
        $this->load->helper('url');
        $this->load->library('pagination');
        $get = $this->input->get() ? $this->input->get() : array();
        unset($get['per_page']);
        $config['base_url'] = base_url() . uri_string() ."?". http_build_query($get);
        $config['total_rows'] = intval($total);
        $config['per_page'] = ($per_page ? $per_page : $this->config->item('per_page'));
        $this->config->load('pagination', TRUE);
        $pagecount = ceil($total/$config['per_page']);
         
        $pagination = $this->config->item('pagination');
        $this->pagination->initialize(array_merge($pagination,$config));
        $link = $this->pagination->create_links();
        return $link;
    }
    
    /**
     * 打印对象或数组
     *
     * @param object $arr 对象或数组
     * @param bool $exit 是否停止
     */
    function pr ($arr = null, $exit = true)
    {
        echo '<pre>';
        if ($arr) {
            print_r(
            is_array($arr) ? $arr : (is_object($arr) ? array('Object', $arr) : array(
            'Not array or object', $arr)));
        } else {
            print_r($this);
        }
        echo '</pre>';
        if ($exit) {
            exit();
        }
    }
    
    /**
     * JSON数据
     * @param $data 数组
     * @param $code 状态嘛
     * @param $msg 提示消息
     */
    public function show_json_data($data = array(), $code = null, $msg = null)
    {
        $this->lang->load('error', 'chinese');
        header("Content-type: application/json;charset=UTF-8");
        $tmpl = array('code' => 'E_200', 'msg' => 'ok', 'data' => $data);
        
        if($data) {
            $tmpl['data'] = $data;
        }
        if($code) {
            if($msg == null) {
                $msg = $this->lang->line($code);
            }
            $opt = array('code' => $code, 'msg' => $msg);
            $tmpl = array_merge($tmpl, $opt);
        }
        
        echo json_encode($tmpl);
    }
    
    /**
     * JSONP数据
     * @param $data 数组
     * @param $code 状态嘛
     * @param $msg 提示消息
     */
    public function show_jsonp_data($data = array(), $code = null, $msg = null)
    {
        $this->lang->load('error', 'chinese');
        $callback = $this->input->get_post('callback') ? $this->input->get_post('callback') : "jsonp";
        header("Content-type: application/json;charset=UTF-8");
        $tmpl = array('code' => 'E_200', 'msg' => 'ok', 'data' => $data);
    
        if($data) {
            $tmpl['data'] = $data;
        }
        if($code) {
            if($msg == null) {
                $msg = $this->lang->line($code);
            }
            $opt = array('code' => $code, 'msg' => $msg);
            $tmpl = array_merge($tmpl, $opt);
        }
        echo $callback . "(" . json_encode($tmpl) . ")";
    }
    
    /**
     * 公共跳转函数
     * @param string $alerts
     * @param string $url
     */
    public function common_jump_url($alerts=NULL,$url=NULL)
    {
        $this->load->library('session');
        $this->load->library('user_agent');
        $this->load->helper('url');
        
        if ($this->agent->is_referral()) {
            $referrer = $this->agent->referrer();
        } else {
            $referrer = $this->uri->uri_string();
        }
        
        $this->session->set_flashdata('alerts', $alerts);
        
        if(empty($url)){
            redirect($referrer);
        }else{
            redirect($url);
        }
        
        return;
    }
    
    
}
